package com.rain.jwt.config;

import com.rain.jwt.util.JwtUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @author: wu
 * @date: 2021/9/25
 */
@Component
@Aspect
public class AuthAspect {
    @Autowired
    private HttpServletRequest request;

    @Pointcut("@annotation(com.rain.jwt.config.Auth)")
    private void authPointcut(){}

    @Around("authPointcut()")
    public Object handleControllerMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取目标对象对应的字节码对象
        Class<?> targetCls=joinPoint.getTarget().getClass();
        //获取方法签名信息从而获取方法名和参数类型
        MethodSignature ms= (MethodSignature) joinPoint.getSignature();
        //获取目标方法对象上注解中的属性值
        Auth auth=ms.getMethod().getAnnotation(Auth.class);
        // 校验签名
        if (auth.token()) {
            String token = JwtUtil.getTokenFromHeader(request);
            JwtUtil.verify(token);
        }
        // 校验签名
        if (auth.sign()) {
            // todo
        }
        return joinPoint.proceed();
    }
}
